package com.szr.leex.service.impl.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.szr.leex.dao.BaseDao;
import com.szr.leex.dao.user.UserDao;
import com.szr.leex.po.user.LocalAuth;
import com.szr.leex.po.user.Role;
import com.szr.leex.po.user.User;
import com.szr.leex.service.impl.BaseServiceImpl;
import com.szr.leex.service.user.LocalAuthService;
import com.szr.leex.service.user.UserService;

/**
 * user service impl
 * Created by WangChen on 2018/10/12 16:37.
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User, String> implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private LocalAuthService localAuthService;

    @Override
    public BaseDao<User, String> getBaseDao() {
        return userDao;
    }

    @Override
    public User getByName(String name) {
        return userDao.findByName(name);
    }

    @Override
    public User register(User user) {
        return userDao.save(user);
    }

    @Override
    public User doRegister(String username, String password, String nickname){
        // 此处省略校验逻辑
        User user = new User();
        user.setName(username);
        user.setCode(username);
        user.setNickname(nickname);

        Role role = new Role();
        role.setName("普通用户");
        role.setCode("USER");

        List<Role> roleList = new ArrayList<>();
        roleList.add(role);
        user.setRoleList(roleList);

        User savedUser = userDao.save(user);


        LocalAuth localAuth = new LocalAuth();
        localAuth.setUserId(savedUser.getId());
        localAuth.setUserName(savedUser.getName());
        localAuth.setPassword(this.encryptPassword(password));
        localAuthService.save(localAuth);

        return savedUser;
    }

    /**
     * 加密密码
     */
    private String encryptPassword(String rawPassword){
        return new BCryptPasswordEncoder().encode(rawPassword);
    }
}
